/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.sys.service.impl;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.renren.common.utils.R;
import io.renren.modules.sys.service.TokenService;
import io.renren.modules.sys.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import io.renren.modules.sys.dao.UserDao;
import io.renren.modules.sys.entity.SmsEntity;
import io.renren.modules.sys.entity.TokenEntity;
import io.renren.modules.sys.entity.UserEntity;
import io.renren.modules.sys.form.LoginForm;
import io.renren.common.shortmessage.sms.SendSms;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
	@Autowired
	private TokenService tokenService;
	@Autowired
	private UserDao userDao;

	@Override
	public UserEntity queryByMobile(String mobile) {
		UserEntity userEntity = new UserEntity();
		userEntity.setMobile(mobile);
		return baseMapper.selectOne(userEntity);

	}

	@Override
	public R login(LoginForm form) {
		//UserEntity user = queryByMobile(form.getMobile());
		/*UserEntity user1 = new UserEntity();
		user1.setMobile(form.getMobile());
		UserEntity user = userDao.getUserByMobile(user1);*/
		Long userId = userDao.getUserIdByMobile(form.getMobile());
		UserEntity user = userDao.getUserByUserId(userId);
		if(user==null) {
		return R.ok("手机号未注册",101);
		}

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			return R.ok("密码错误",101);
		}

		//获取登录token
		TokenEntity tokenEntity = tokenService.checkToken(user.getUserId());
	if(tokenEntity != null &&(tokenEntity.getExpireTime().getTime() - System.currentTimeMillis()) > 0  ) {
		Map<String, Object> map = new HashMap<>(2);
		map.put("token", tokenEntity);
		map.put("isAuthentication", user.getIsAuthentication());
		map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());
		map.put("isOneLogin", user.getIsOneLogin());
		if (user.getStatus() == 1) {
			return R.ok("此用户已被禁用", 101);
		}
		if (0 == user.getIsOneLogin()) {
			//修改成已经登陆过 1
			Map m = new HashMap();
			m.put("userId", userId);
			userDao.updateIsOneLogin(m);
		}
		return R.ok("登录成功", 100).put("data", map);
	}
		else{
			TokenEntity newtokenEntity = tokenService.createToken(user.getUserId());
			Map<String, Object> map = new HashMap<>(2);
			map.put("token", newtokenEntity);
			map.put("isAuthentication",user.getIsAuthentication());
			map.put("expire", newtokenEntity.getExpireTime().getTime() - System.currentTimeMillis());
			map.put("isOneLogin",user.getIsOneLogin());
			if(user.getStatus()==1){
				return R.ok("此用户已被禁用",101);
			}
			if(0 == user.getIsOneLogin()){
				//修改成已经登陆过 1
				Map m = new HashMap();
				m.put("userId",userId);
				userDao.updateIsOneLogin(m);
			}
			return R.ok("登录成功",100).put("data",map);
		}
	}

	@Override
	public UserEntity QQlogin(String QQUid) {
		UserEntity u=userDao.findByqqUid(QQUid);
		return u;
	}

	@Override
	public void sendSms(String mobile) {
		Integer i= SendSms.getRandNum(100000,999999);
		SendSmsResponse sendResult=	SendSms.send(mobile,i.toString());
		if(sendResult.getCode().equals("OK")) {
			SmsEntity smsEntity=new SmsEntity();
			smsEntity.setMobile(mobile);
			smsEntity.setCode(i.toString());
			userDao.saveSms(smsEntity);
		}
		System.out.println(sendResult);
	}

	@Override
	public SmsEntity getSmsEntityByCode(SmsEntity smsEntity) {
		return userDao.getSmsEntityByCode(smsEntity);
	}

	@Override
	public UserEntity queryByQQuid(String qqUid) {
		return userDao.findByqqUid(qqUid);
	}

	@Override
	public void deleteByQQuid(String qqUid) {
		userDao.deleteByQQuid(qqUid);
	}

	@Override
	public UserEntity queryByOpenId(String openId) {
		return null;
	}

	@Override
	public void deleteByOpenId(String qqUid) {

	}

	/**
	 * 修改用户名
	 */
	@Override
	public void upadateUserNameByUserId(UserEntity u) {
		userDao.upadateUserNameByUserId(u);
	}

	/**
	 * 修改性别
	 */
	@Override
	public void upadateSexByUserId(UserEntity u) {
		userDao.upadateSexByUserId(u);
	}

	/**
	 * 修改年龄
	 */
	@Override
	public void upadateAgeByUserId(UserEntity u) {
		userDao.upadateAgeByUserId(u);
		
	}

	/**
	 * 修改地址
	 */
	@Override
	public void upadateAddressByUserId(UserEntity u) {
		userDao.upadateAddressByUserId(u);
		
	}

	/**
	 * 根据userId获取用户密码
	 */
	@Override
	public String selectPasswordByUserId(Long userId) {
			return userDao.selectPasswordByUserId(userId);
	}

	/**
	 * 在登录状态下进行密码的修改
	 */
	@Override
	public void upadatePasswordOnLogin(UserEntity u) {
		userDao.upadatePasswordOnLogin(u);
	}

	/**
	 * 通过userId寻找当前用户的手机号
	 * @param userId
	 * @return
	 */
	@Override
	public String selectMobileByUserId(Long userId) {

		return userDao.selectMobileByUserId(userId);
	}

	/**
	 * 根据手机号查询验证码
	 * @param newMobile
	 * @return
	 */
	@Override
	public String getCodeByMobile(String newMobile) {
		return userDao.getCodeByMobile(newMobile);
	}

	@Override
	public void updateMobileByUserId(UserEntity user) {
		userDao.updateMobileByUserId(user);
	}

	@Override
	public Long getUserIdByMobile(String mobile) {
		return userDao.getUserIdByMobile(mobile);
	}

	/**
	 * 修改头像
	 * @param user
	 */
	@Override
	public void updateHeadImageByUserId(UserEntity user) {
		userDao.updateHeadImageByUserId(user);
	}

	/**
	 * 根据id查询手机号
	 * @param userId
	 * @return
	 */
	@Override
	public String getMobileByUserId(Long userId) {
		return userDao.getMobileByUserId(userId);
	}

	/**
	 * 根据id查询用户信息
	 * @param id
	 * @return
	 */
	@Override
	public UserEntity getUserByUserId(Long id) {
		return userDao.getUserByUserId(id);
	}

	@Override
	public String getTokenByUserId(Long userId) {
		return userDao.getTokenByUserId(userId);
	}

	@Override
	public List<UserEntity> selectUserByMobile(String newMobile) {
		return userDao.selectUserByMobile(newMobile);
	}

	@Override
	public UserEntity getNewUser() {
		return userDao.getNewUserId();
	}

	@Override
	public void updateOpenIdByuserId(UserEntity userEntity) {
		userDao.updateOpenIdByuserId(userEntity);
	}

	@Override
	public UserEntity getUserByOpenId(UserEntity userEntity) {
		return userDao.getUserByOpenId(userEntity);
	}

	@Override
	public void updateUserByMobile(UserEntity userEntity) {
		userDao.updateUserByMobile(userEntity);
	}

	@Override
	public void updateImaAndNickByMobile(UserEntity userEntity) {
		userDao.updateImaAndNickByMobile(userEntity);
	}

	@Override
	public UserEntity getUserByToken(String token) {
		return userDao.getUserByToken(token);
	}

	@Override
	public void updateIsBangDingQQOrWeChat(UserEntity userEntity) {
		userDao.updateIsBangDingQQOrWeChat(userEntity);
	}

	@Override
	public List<Long> getSameSchoolUserIds(Integer schoolId) {
		return userDao.getSameSchoolUserIds(schoolId);
	}

	@Override
	public void updateNickNameB(UserEntity userEntity) {
		userDao.updateNickNameB(userEntity);
	}

	@Override
	public Byte[] getNickNameById(Long userId) {
		return userDao.getNickNameById(userId);
	}

	@Override
	public void updateNickNameById(UserEntity userEntity) {
		userDao.updateNickNameById(userEntity);
	}

	@Override
	public int getSchoolIdByUserId(Map map) {
		return userDao.getSchoolIdByUserId(map);
	}

	@Override
	public List getForYoungById(Long id) {
		return userDao.getForYoungById(id);
	}

	@Override
	public List getUserIdBySchoolId(int schoolId) {
		return userDao.getUserIdBySchoolId(schoolId);
	}

	@Override
	public void updateIsOneLogin(Map m) {
		userDao.updateIsOneLogin(m);
	}

	@Override
	public List getWork() {
		return userDao.getWork();
	}

	@Override
	public void updateUserWork(Map map) {
		userDao.updateUserWork(map);
	}

	@Override
	public List getLable() {
		return userDao.getLable();
	}
}
